import os
import shutil
import uuid

from fastapi import APIRouter, UploadFile

from app.utils.face import check_face
from app.utils.response import success, error
from app.utils.upload import allowed_image

router = APIRouter(prefix="/upload", tags=["upload"])


@router.post("/face")
def upload_face(face: UploadFile):
    # 检查图片类型
    if not allowed_image(face.filename):
        return error("请上传正确的图片")

    # 生成随机文件名
    file_extension = face.filename.rsplit('.', 1)[1].lower()
    random_filename = f"{uuid.uuid4().hex}.{file_extension}"

    # 指定保存路径
    save_path = f"uploads/{random_filename}"

    # 确保 uploads 目录存在
    os.makedirs("uploads", exist_ok=True)

    # 将文件内容写入到指定路径
    with open(save_path, "wb") as buffer:
        shutil.copyfileobj(face.file, buffer)

    # 关闭文件
    face.file.close()

    # 检查是否有人脸
    flag = check_face(save_path)
    if not flag:
        os.remove(save_path)
        return error("图片中没有人脸,或者出现多个人脸")

    return success("上传成功", {"file_name": random_filename, "file_url": save_path})
